//
//  TWMomentsViewModel.m
//  TWHomework-WeChat
//
//  Created by wzb on 2019/11/13.
//  Copyright © 2019 WZB. All rights reserved.
//

#import "TWMomentsViewModel.h"
#import "TWBaseRequestModel.h"
#import "Define.h"
#import <YYModel/YYModel.h>
#import "TWUserInfo.h"
#import "TWBaseReponseModel.h"
#import "TWCacheHelper.h"
#import "TWTweet.h"
#import "NSArray+TW.h"

@implementation TWMomentsViewModel

/**
 获取用户信息
 
 @param success 成功回调
 @param failure 失败回调
 */
- (void)getUserInfo:(TWSuccessBlock)success failure:(TWFailureBlock)failure
{
    // 先从缓存取出来
    NSDictionary *userInfo = [TWCacheHelper getCacheDictionaryForKey:kUserInfo];
    if (userInfo) {
        self.user = [TWUserInfo yy_modelWithJSON:userInfo];
        if (success) {
            success(self.user);
        }
        return;
    }
    // 如果缓存中没有，再从网络取
    TWBaseRequestModel *request = [TWBaseRequestModel newWithCaller:self Path:kGetUserInfoAPIPath];
    [[TWWebClient sharedClient] request:request success:^(TWBaseReponseModel *response) {
        self.user = [TWUserInfo yy_modelWithJSON:response.response];
        if (success) {
            success(self.user);
        }
        // 缓存用户信息
        [TWCacheHelper cacheKeyValues:response.response forKey:kUserInfo];
    } failure:^(NSURLSessionDataTask *operation, NSError *e) {
        if (failure) {
            failure(@"请求失败，请重试");
        }
    }];
}

/**
 获取tweets列表
 
 @param success 成功回调
 @param failure 失败回调
 */
- (void)getTweets:(TWSuccessBlock)success failure:(TWFailureBlock)failure
{
    TWBaseRequestModel *request = [TWBaseRequestModel newWithCaller:self Path:kGtweetsAPIPath];
    [[TWWebClient sharedClient] request:request success:^(TWBaseReponseModel *response) {
        // 过滤无效数据
        NSArray *dataArr = [response.response tw_filterWithBlock:^BOOL(NSDictionary *data) {
            return !([data valueForKey:@"error"] || [data valueForKey:@"unknown error"] || (![data valueForKey:@"content"] && ![data valueForKey:@"images"]));
        }];
        self.tweets = [NSArray yy_modelArrayWithClass:TWTweet.class json:dataArr];
        if (success) {
            success(self.tweets);
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *e) {
        if (failure) {
            failure(@"请求失败，请重试");
        }
    }];
}

@end
